<!--
/// 
/// MaDAson - Toolkit for Model Driven Software Development
///
/// Copyright [2006] Marcus Lankenau
/// 
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///  
///     http://www.apache.org/licenses/LICENSE-2.0
///  
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
/// 
-->
<%@ Page Language="C#" %>
<%@ Import Namespace="Madason.MetaModel" %>
<%@ Import Namespace="Madason.MetaModel.DAO" %>
package <%= Package %>;

import java.sql.Connection;
import java.sql.SQLException;

import org.madason.humanresources.datalayer.DBUtil;

import net.sf.click.Page;
import net.sf.click.control.Field;
import net.sf.click.control.Form;
import net.sf.click.control.HiddenField;
import net.sf.click.control.Submit;
import net.sf.click.control.TextField;
import net.sf.click.control.Select;
import net.sf.click.control.Option;
import net.sf.click.extras.control.NumberField;
import net.sf.click.extras.control.DateField;

public class <%= Class.Name %>EditPage extends Page 
{
	public <%= Class.PrimaryKey.Type.Name %> loadid;
	public String error = "";
	
	/* controls */
<% foreach (PersistedAttribute attr in Class.Attributes) { %>		
	private Field <%= attr.Name %>Field = null;
<% } %>				
<% foreach (Association assoc in Class.ActiveAssociations) { %>	
	private Field <%= assoc.Name %>Field = null;
<% } %>	
	private HiddenField state = new HiddenField("state", "");
	
	public <%= Class.Name %>EditPage()
	{		
<% foreach (PersistedAttribute attr in Class.Attributes) { %>		
		addControl(<%= attr.Name %>Field = createField<%= attr.NamePascalCase %>());
<% } %>		
		
<% foreach (Association assoc in Class.ActiveAssociations) { %>			
		addControl(<%= assoc.Name %>Field = createField<%= assoc.NamePascalCase %>());
<% } %>		
		addControl(state);
		addControl(new Submit("save", "  Save  ", this, "onSaveClick"));
		addControl(new Submit("cancel", this, "onCancelClick"));     
		Submit deleteSubmit = new Submit("delete", "  Delete  ", this, "onDeleteClick");
		deleteSubmit.setAttribute("onclick", "return confirm('are you sure you want to delete this object');");
		addControl(deleteSubmit);
	}
	
	protected void fillForm(<%= Class.ExplicitName %> bean)
	{
<% foreach (PersistedAttribute attr in Class.Attributes) { %>		
<%   if (attr.Type.Name == "String") { %>
		<%= attr.Name %>Field.setValue(bean.get<%= attr.NamePascalCase %>());
<%   } else if (attr.Type.Name == "Date") { %>
		((DateField)<%= attr.Name %>Field).setDate(bean.get<%= attr.NamePascalCase %>());	
<%   } else  { %>	
		<%= attr.Name %>Field.setValue(""+bean.get<%= attr.NamePascalCase %>());
<%   } %>			
<% } %>	
<% foreach (Association assoc in Class.ActiveAssociations) { %>			
		<%= assoc.Name%>Field.setValue(""+bean.get<%= assoc.NamePascalCase%>());
<% } %>				
	}
	
	protected void readForm(<%= Class.ExplicitName %> bean)
	{
<% foreach (PersistedAttribute attr in Class.Attributes) { %>		
<%   if (attr.Type.Name == "String") { %>
		bean.set<%= attr.NamePascalCase %>(<%= attr.Name %>Field.getValue());
<%   } else if (attr.Type.Name == "Date") { %>
		bean.set<%= attr.NamePascalCase %>(((DateField)<%= attr.Name %>Field).getDate());
<%   } else if (attr.Type.Name == "int") { %>	
		bean.set<%= attr.NamePascalCase %>(Integer.parseInt(<%= attr.Name %>Field.getValue()));
<%   } else if (attr.Type.Name == "float") { %>	
		bean.set<%= attr.NamePascalCase %>(Float.parseFloat(<%= attr.Name %>Field.getValue()));
<%   } else if (attr.Type.Name == "double") { %>	
		bean.set<%= attr.NamePascalCase %>(Double.parseDouble(<%= attr.Name %>Field.getValue()));
<%   } %>			
<% } %>	
<% foreach (Association assoc in Class.ActiveAssociations) { %>			
<%   if (((Entity)assoc.TargetClass).PrimaryKey.Type.Name == "int") { %>
		bean.set<%= assoc.NamePascalCase%>(Integer.parseInt(<%= assoc.Name%>Field.getValue()));
<%   } else if (((Entity)assoc.TargetClass).PrimaryKey.Type.Name == "String") { %>
		bean.set<%= assoc.NamePascalCase%>(<%= assoc.Name%>Field.getValue());		
<%   } %>			
<% } %>				
	}	
	
	public void onGet()
	{
		super.onGet();
		
		<% if (Class.PrimaryKey.Type.Name == "int") { %>
		if (loadid != 0)
		<% } else if (Class.PrimaryKey.Type.Name == "String") { %>
		if (loadid != null && loadid.length() > 0)
		<% } %>			
		{			
			Connection conn = null;
			try
			{
				conn = DBUtil.getConn();
				<%= Class.ExplicitName %>Access access = <%= Class.ExplicitName%>Access.getInstance();
				<%= Class.ExplicitName%> bean = access.findByPrimaryKey(conn, loadid);
				if (bean != null)
				{
					fillForm(bean);				
					state.setValue("existing");
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			finally
			{
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
		}
		
		
	}


	public void onRender() {
		boolean pkReadonly = "existing".equals(state.getValue());
		<%= Class.PrimaryKey.Name %>Field.setReadonly(pkReadonly);
		super.onRender();
	}


	public boolean onDeleteClick()
	{
	
		<% if (Class.PrimaryKey.Type.Name == "int") { %>
		int pk = Integer.parseInt(<%= Class.PrimaryKey.Name %>Field.getValue());
		<% } else if (Class.PrimaryKey.Type.Name == "String") { %>
		String pk = <%= Class.PrimaryKey.Name %>Field.getValue();
		<% } %>		
	
	
		Connection conn = null;
		try
		{
			conn = DBUtil.getConn();
			<%= Class.ExplicitName %>Access access = <%= Class.ExplicitName%>Access.getInstance();
			access.delete(conn, pk);
			setRedirect("<%= Class.NameCamelCase %>List.htm");
			return false;			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}	
	
		return false;
	}
	
	public boolean onSaveClick()
	{			
		boolean hasErrors = false;
		
<% foreach (PersistedAttribute attr in Class.Attributes) { %>				
		if (!<%= attr.Name %>Field.isValid())
		{
			<%= attr.Name %>Field.setStyle("background-color", "ff6060");
			hasErrors = true;
		}
<% } %>	
		if (hasErrors) {
			error = "your input has errors";
			return true;
		}
	
	
		Connection conn = null;
		try
		{		
			String idFieldValue = <%= Class.PrimaryKey.Name %>Field.getValue();
			<% if (Class.PrimaryKey.Type.Name == "int") { %>
			int id = "".equals(idField) ? 0 : Integer.parseInt(idFieldValue);
			<% } else if (Class.PrimaryKey.Type.Name == "String") { %>
			String id = idFieldValue;
			<% } %>			
			conn = DBUtil.getConn();
			<%= Class.ExplicitName%>Access access = <%= Class.ExplicitName%>Access.getInstance();
			<%= Class.ExplicitName%> bean = access.findByPrimaryKey(conn, id);
			if ("".equals(state.getValue()))
			{
				bean = new <%= Class.ExplicitName%>();
				readForm(bean);
				access.insert(conn, bean);
				fillForm(bean);
				state.setValue("existing");
			}
			else
			{	
				readForm(bean);
				access.update(conn, bean);
			}						
			conn.commit();
		}
		catch (Exception e)
		{
			error = e.getMessage();
			e.printStackTrace();
		}
		finally
		{
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		return true;
	}

	
	public boolean onCancelClick()
	{
		setRedirect("<%= Class.NameCamelCase %>List.htm");
		return false;
	}

<% foreach (PersistedAttribute attr in Class.Attributes) { %>			
	protected Field createField<%= attr.NamePascalCase %>()
	{
<% if (attr.Type.Name == "Date") { %>		
		DateField field =  new DateField("<%= attr.Name%>Field");
		field.setFormatPattern("dd.MM.yyyy");
		field.setRequired(true);
		return field;
<% } else  if (attr.Type.Name == "float" || attr.Type.Name == "double") { %>		
		NumberField field = new NumberField("<%= attr.Name %>Field");
		field.setRequired(true);
		return field;
<% } else { %>
		return new TextField("<%= attr.Name %>Field");
<% } %>			
	}
<% } %>		

<% foreach (Association assoc in Class.ActiveAssociations) { %>			
	protected Field createField<%= assoc.NamePascalCase %>()
	{
<% if (assoc.TargetClass.Operations["findAll"] == null) { %>
		return new TextField("<%= assoc.Name %>Field");
<% } else { %>
		<%= assoc.TargetClass.ExplicitName %>Access access = <%= assoc.TargetClass.ExplicitName%>Access.getInstance();
		Select select = new Select("<%= assoc.Name %>Field");
		Connection conn = null;
		try
		{
			conn = DBUtil.getConn();
			java.util.List<%= "<" + assoc.TargetClass.ExplicitName + ">"%> beans = access.findAll(conn);
					
			select.add(new Option("0", "-"));	
			for (<%= assoc.TargetClass.ExplicitName%> bean : beans)			
				select.add(new Option(bean.get<%= (assoc.TargetClass as Entity).PrimaryKey.NamePascalCase %>(), bean.<%= getGetterFirstStringAttribute(assoc.TargetClass)%>()));
		}
		catch (Exception e)
		{
			error = e.getMessage();
		}
		finally
		{
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}		
		}
				
		return select;
<% } %>		
	
	}
<% } %>		

}


<script runat="server">
	private Entity @class;
	private string package;

	
	public String getGetterFirstStringAttribute(Class cls)
	{
		foreach (Madason.MetaModel.Attribute attr in cls.Attributes)
		{
			if (attr.Type.Name == "String")
				return "get"+attr.NamePascalCase;
		}
		
		
		return "toString";	
	}
		
	
	public string Package
	{
		get { return package; }
		set { package = value; }
	}
	
	public PersistedAttribute PrimaryKey
	{
		get
		{
			return this.Class.PrimaryKey;
		}
	}

	public Entity Class
	{
		get { return @class; }
		set { @class = value; }
	}

</script>